using LuckyWinner.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Diagnostics;
using System.IO;

namespace LuckyWinner.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(string name, string email)
        {
            string docPath = "Emails";

            if (!Directory.Exists(docPath))
                Directory.CreateDirectory(docPath);


            using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "userdata.txt"), true))
            {
                outputFile.WriteLine(name + ", " + email);
            }
            ViewBag.Submitted = "Yes";

            return View();
        }

        public IActionResult User()
        {
            string docPath = "Emails";
            string allData = string.Empty;
            try
            {
                using (StreamReader reader = new StreamReader(Path.Combine(docPath, "userdata.txt")))
                {
                    while (reader.Peek() >= 0)
                    {
                        string line = reader.ReadLine();
                        allData += "<tr><td>" + line.Split(',')[0] + "</td><td>" + line.Split(',')[1] + "</td></tr>";
                    }
                }
            }
            catch
            {
            }

            ViewBag.Users = allData;

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
